package com.client.util;

import java.util.HashMap;

/**
 * @author Zixiang Hu
 * @description 单例工厂
 * @create 2021-03-04-16:00
 */
public class SingletonFactory {
    private static final HashMap<Class, Object> OBJECT_HASH_MAP = new HashMap<>();

    /**
     * 私有化构造器
     */
    private SingletonFactory() {

    }

    public static <T> T getObject(Class<T> clazz) {
        Object instance = OBJECT_HASH_MAP.get(clazz);
        synchronized (clazz) {
            if (instance == null) {
                try {
                    instance = clazz.newInstance();
                    OBJECT_HASH_MAP.put(clazz, instance);
                } catch (IllegalAccessException | InstantiationException e) {
                    throw new RuntimeException(e.getMessage(), e);
                }
            }
        }
        return clazz.cast(instance);
    }
}
